package com.qf.index.gcrdo;


import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * <dependency>
 * <groupId>com.squareup.okhttp3</groupId>
 * <artifactId>okhttp</artifactId>
 * <version>4.9.3</version>
 * </dependency>
 *
 * <dependency>
 * <groupId>com.alibaba</groupId>
 * <artifactId>fastjson</artifactId>
 * <version>1.2.79</version>
 * </dependency>
 */

/**
 * @Author: 张福垒
 * @Date: 2024/10/08 10:26
 * @Description:
 * @phone: 13864677931
 */
@Slf4j
public class TongYiApi {

    public static void main(String[] args) throws Exception {


        // 药物，数字代号：1; 基因，数字代号：2; 通路，数字代号：3; 疾病，数字代号：4
        Db use = Db.use(DSFactory.get("localdb"));
        Map<Integer, String> mapType = new LinkedHashMap<>();
        mapType.put(1, "药物");
        mapType.put(2, "基因");
        mapType.put(3, "通路");
        mapType.put(4, "疾病");
        List<Entity> query = use.query("select * from word_and_code_set_map_new where tongyi_back is null");
        for (Entity entity : query) {
            String codeSet = entity.getStr("code_set");
            if (StringUtil.isNotNull(codeSet)) {
                List<Integer> integers = JSONArray.parseArray(codeSet, Integer.class);
                if (integers.size() == 1) {
                    String word = entity.getStr("word");
                    String question = "你是一名医学方面专家 请判断下面这个词" + word + "是不是" + mapType.get(integers.get(0)) + "范畴,请回答是或者不是不要回答其他信息";
                    System.out.println("问题+++" + question);
                    String s = send(question);
                    if (StringUtil.isNotNull(s)) {
                        System.out.println("word_id+" + entity.getInt("id") +"++"+ word + "++是不是" + mapType.get(integers.get(0)) + "_s_" + s);
                        entity.set("tongyi_back", s);
                        use.insertOrUpdate(entity, "id");
                    }
                }else {
                    // 设计多个维度的 存储结果使用json 数据 分别是类型 value 和对应的是不是
                    log.info("通义多维度+++{}",integers);
                    Map<String,String> resultMap = new LinkedHashMap<>();
                    for (Integer integer : integers) {
                        String word = entity.getStr("word");
                        String question = "你是一名医学方面专家 请判断下面这个词" + word + "是不是" + mapType.get(integer) + "范畴,请回答是或者不是不要回答其他信息";
                        System.out.println("问题+++" + question);
                        String s = send(question);
                        if (StringUtil.isNotNull(s)) {
                            resultMap.put(mapType.get(integer),s);
                        }
                    }
                    if (resultMap.size() > 0) {
                        System.out.println(resultMap);
                        entity.set("tongyi_back", JSONObject.toJSONString(resultMap));
                        use.insertOrUpdate(entity, "id");
                    }
                }
            }
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        }
    }

    public static String send(String question) throws IOException, InterruptedException {
        Thread.sleep(1000);
        List<MsgEntity> msgEntities = new ArrayList<>();

        msgEntities.add(new MsgEntity("user", question));


        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(100, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        Request request = sendMsg(msgEntities);
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {

            e.printStackTrace(System.err);
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (null != response) {
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                InputStream inputStream = responseBody.byteStream();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
//                        System.out.println("BAOCUO__" + line);
//                        System.out.println("info_" + question);
                        if ("[DONE]".equals(line) || "data: [DONE]".equals(line)) {
                            break;
                        }
                        line = line.replaceAll("data: ", "").trim();
                        try {
                            if (isNotNull(line)) {
                                ChatCompletionChunk chatCompletionChunk = JSONObject.parseObject(line, ChatCompletionChunk.class);
                                List<Choice> choices = chatCompletionChunk.getChoices();


                                for (Choice choice : choices) {
                                    String content = choice.getDelta().getContent().replaceAll("\n\n", "\n");
                                    if (isNotNull(content)) {
                                        stringBuilder.append(content);
                                    }
                                }

//                                for (Choice choice : choices) {
//                                    String content = choice.getDelta().getContent().replaceAll("\n\n", "\n");
//                                    char[] charArray = content.toCharArray();
//                                    for (char c : charArray) {
//                                        System.out.print("\033[32m" + c + "\033[0m");
//                                        Thread.sleep(20);
//                                        stringBuilder.append(c);
//                                        outputStream.write(("" + c).getBytes(StandardCharsets.UTF_8));
//                                        outputStream.flush();
//                                    }
//                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace(System.err);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
        return stringBuilder.toString();
    }


    public static Request sendMsg(List<MsgEntity> msgEntities) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("messages", JSONObject.toJSONString(msgEntities));
        map.put("model", "\"qwen-plus-1127\"");
        map.put("frequency_penalty", 0);
        map.put("max_tokens", 2000);
        map.put("presence_penalty", 0);
        map.put("stop", null);
        map.put("stream", true);
        map.put("temperature", 1);
        map.put("top_p", 0.9);
        String string = mapToString(map);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, string);
        Request request = new Request.Builder().url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-c65ee8baf0c440238e51f74495107da3")
                .build();
        return request;
    }

    @Data
    public static class ChatCompletionChunk {
        private String id;
        private List<Choice> choices;
        private long created;
        private String model;
        private String system_fingerprint; // 由于示例中为null，这里使用Object类型
        private String object;
    }

    @Data
    public static class Choice {
        private int index;
        private Delta delta;
        private Object finish_reason; // 由于示例中为null，这里使用Object类型
        private Object logprobs;
    }

    @Data
    public static class Delta {
        private String content;
        private String role;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Accessors(chain = true)
    public static class MsgEntity {
        private String role;
        private String content;
    }

    public static String mapToString(Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (stringBuilder.length() > 1) { // 避免第一个元素前出现逗号
                stringBuilder.append(",");
            }
            String key = entry.getKey();
            Object value = entry.getValue();
            stringBuilder.append("\"").append(key).append("\":").append(value);
        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    public static boolean isNotNull(String str) {
        return str != null && !str.trim().isEmpty() && !"null".equals(str);
    }
}


